<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">















 
 
 
 
 
 
 
  
  


<html>
  <head>
    <script type="text/javascript" language="JavaScript">
    ORIGINAL_PAGE_PATH = "/appengine/docs/java/datastore/creatinggettinganddeletingdata.html";
    </script>
    
    
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Creating, Getting and Deleting Data - Google App Engine - Google Code</title>
<script type="text/javascript"><!--
(function(){function a(){this.t={};this.tick=function(c){this.t[c]=(new Date).getTime()};this.tick("start")}var b=new a;window.jstiming={Timer:a,load:b};if(window.external&&window.external.pageT)window.jstiming.pt=window.external.pageT;})();

var _tocPath_ = '/appengine/docs/_toc.ezt';
var codesite_token = null;
//--></script>
<link href="../../../../css/codesite.pack.04102009.css" type="text/css" rel="stylesheet"></link>
<script src="../../../../js/codesite_head.pack.04102009.js" type="text/javascript"></script>
<script type="text/javascript">CODESITE_CSITimer['load'].tick('bhs');</script>
<link rel="search" type="application/opensearchdescription+xml" title="Google Code" href="http://code.google.com/osd.xml" />

<!--[if IE]><link rel="stylesheet" type="text/css" href="../../../../css/iehacks.css" /><![endif]-->

    <link href="../../../../css/semantic_headers.css" rel="stylesheet" type="text/css" />
    <link href="../../../css/local_extensions.css" rel="stylesheet" type="text/css" />
  </head>

  <body class="gc-documentation">

    
    
    
</a>

<div id="gb">
 <span>
  
    <a id="lang-dropdown" class="dropdown" href="http://code.google.com" onclick="return false;"><img class="globeicon" src="../../../../images/globe2_small.png"/><span>English</span></a>
  
 </span>
</div>

<div class="gbh" style="left: 0pt;"></div>
<div class="gbh" style="right: 0pt;"></div>


<style type="text/css">
  #gc-topnav h1 {
    padding: 0 0 0 6px;
  }
</style>


<div id="gc-container">
<a name="top"></a>
<div id="skipto">
  <a href="#gc-pagecontent">Skip to page content</a>
  <a href="#gc-toc">Skip to main navigation</a>
</div>

<div id="gc-header">
  <div id="logo"><a href="http://code.google.com">
  
  
     <img src="../../../../images/cleardot.gif" height="1px" width="1px" alt="Google Code Home Page" id="gc-logo-img"/>
  
  
  </a></div>
  <div id="search">
    <div id="searchForm" class="searchForm">
      <form id="cse" action="http://www.google.com/cse" accept-charset="utf-8" class="gsc-search-box" onsubmit="executeGSearch(document.getElementById('gsearchInput').value); return false;">
      <noscript>
      <input type="hidden" name="cref" value="http://code.google.com/cse/googlecode-context.xml"/>
      </noscript>
        <table class="gsc-search-box" cellpadding="0" cellspacing="0">
          <tbody>
            <tr>
              <td class="gsc-input">
                <input id="gsearchInput" type="text" name="q" maxlength="2048" class="gsc-input" autocomplete="off" title="Google Code Search" style="width:345px"/>
              </td>
              <td class="gsc-search-button">
                <div id="cs-searchresults" onclick="event.cancelBubble = true;"></div>
                <input title="Search" id="gsearchButton" class="gsc-search-button" name="sa" value="Search" type="submit"/>
              </td>
            </tr>
            <tr>
              <td colspan="2" class="greytext">e.g. "templates" or "datastore"</td>
            </tr>
          </tbody>
        </table>
      </form>
    </div> <!-- end searchForm -->
  </div> <!-- end search -->
</div> <!-- end gc-header -->


<div id="codesiteContent">

<a name="gc-topnav-anchor"></a>
<div id="gc-topnav">
  <h1>Google App Engine</h1>
  <ul id="docs" class="gc-topnav-tabs">

    <li id="home_link">
      <a href="../../../index.html" title="Google App Engine home page">Home</a>
    </li>
  
    <li id="docs_link">
      <a href="../../index.html" class="selected" title="Official Google App Engine documentation">Docs</a>
    </li>
  
    <li id="faq_link">
      <a href="../../../kb/index.html" title="Answers to frequently asked questions about Google App Engine">FAQ</a>
    </li>
  
    <li id="articles_link">
      <a href="../../../articles/index.html" title="Focused articles and tutorials for Google App Engine developers">Articles</a>
    </li>
  
    <li>
      <a href="http://googleappengine.blogspot.com/" title="Official Google App Engine blog">Blog</a>
    </li>
  
    <li>
      <a href="../../../community.html" title="Community home for Google App Engine">Community</a>
    </li>
  
    <li>
      <a href="../../../terms.html" title="Google App Engine terms of service">Terms</a>
    </li>
  
    <li>
      <a href="../../../downloads.html" title="Download Google App Engine">Download</a>
    </li>
  

  </ul>
</div> <!-- end gc-topnav -->

    <div class="g-section g-tpl-170">

      <div class="g-unit g-first" id="gc-toc">
        <ul>
  <li><a href="../../../downloads.html">Downloads</a></li>
  <li><a href="http://code.google.com/status/appengine">System Status</a></li>
  <li><a href="http://code.google.com/p/googleappengine/issues/list">Issue Tracker</a></li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Getting Started</h2>
    <ul>
      <li><a href="../../whatisgoogleappengine.html">What Is Google App Engine?</a></li>
      <li><a href="../gettingstarted/index.html">Java</a>
        <ul>
              <li><a href="../gettingstarted/introduction.html">Introduction</a></li>
    <li><a href="../gettingstarted/installing.html">Installing the Java SDK</a></li>
    <li><a href="../gettingstarted/creating.html">Creating a Project</a></li>
    <li><a href="../gettingstarted/usingusers.html">Using the Users Service</a></li>
    <li><a href="../gettingstarted/usingjsps.html">Using JSPs</a></li>
    <li><a href="../gettingstarted/usingdatastore.html">Using the Datastore with JDO</a></li>
    <li><a href="../gettingstarted/staticfiles.html">Using Static Files</a></li>
    <li><a href="../gettingstarted/uploading.html">Uploading Your Application</a></li>

        </ul>
      </li>
      <li><a href="../../python/gettingstarted/index.html">Python</a>
        <ul>
            <li><a href="../../python/gettingstarted/introduction.html">Introduction</a></li>
  <li><a href="../../python/gettingstarted/devenvironment.html">The Development Environment</a></li>
  <li><a href="../../python/gettingstarted/helloworld.html">Hello, World!</a></li>
  <li><a href="../../python/gettingstarted/usingwebapp.html">Using the webapp Framework</a></li>
  <li><a href="../../python/gettingstarted/usingusers.html">Using the Users Service</a></li>
  <li><a href="../../python/gettingstarted/handlingforms.html">Handling Forms With webapp</a></li>
  <li><a href="../../python/gettingstarted/usingdatastore.html">Using the Datastore</a></li>
  <li><a href="../../python/gettingstarted/templates.html">Using Templates</a></li>
  <li><a href="../../python/gettingstarted/staticfiles.html">Using Static Files</a></li>
  <li><a href="../../python/gettingstarted/uploading.html">Uploading Your Application</a></li>

        </ul>
      </li>
    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Java <sup class="new">Early Look</sup></h2>
    <ul>
          <li><a href="../overview.html">Overview</a></li>
    <li><a href="../runtime.html">Servlet Environment</a></li>
    <li><a href="index.html">Storing Data</a>
      <ul>
            <li><a href="overview.html">Overview</a></li>
    <li><a href="usingjdo.html">Using JDO</a></li>
    <li><a href="dataclasses.html">Defining Data Classes</a></li>
    <li><a href="creatinggettinganddeletingdata.html">Creating, Getting and Deleting Data</a></li>
    <li><a href="queriesandindexes.html">Queries and Indexes</a></li>
    <li><a href="transactions.html">Transactions</a></li>
    <li><a href="relationships.html">Relationships</a></li>
    <li><a href="usingjpa.html">Using JPA</a></li>
    <li><a href="../javadoc/com/google/appengine/api/datastore/package-summary.html">Low-level API</a></li>

      </ul>
    </li>
    <li><a href="../apis.html">Services</a>
      <ul>
        <li><a href="../memcache/index.html">Memcache</a>
          <ul>
                <li><a href="../memcache/overview.html">Overview</a></li>
    <li><a href="../memcache/usingjcache.html">Using JCache</a></li>
    <li><a href="../javadoc/com/google/appengine/api/memcache/package-summary.html">Low-level API</a></li>

          </ul>
        </li>
        <li><a href="../urlfetch/index.html">URL Fetch</a>
          <ul>
                <li><a href="../urlfetch/overview.html">Overview</a></li>
    <li><a href="../urlfetch/usingjavanet.html">Using java.net</a></li>
    <li><a href="../javadoc/com/google/appengine/api/urlfetch/package-summary.html">Low-level API</a></li>

          </ul>
        </li>
        <li><a href="../mail/index.html">Mail</a>
          <ul>
                <li><a href="../mail/overview.html">Overview</a></li>
    <li><a href="../mail/usingjavamail.html">Using JavaMail</a></li>
    <li><a href="../javadoc/com/google/appengine/api/mail/package-summary.html">Low-level API</a></li>

          </ul>
        </li>
        <li><a href="../images/index.html">Images</a>
          <ul>
                <li><a href="../images/overview.html">Overview</a></li>
    <li><a href="../javadoc/com/google/appengine/api/images/package-summary.html">API Reference</a></li>

          </ul>
        </li>
        <li><a href="../users/index.html">Google Accounts</a>
          <ul>
                <li><a href="../users/overview.html">Overview</a></li>
    <li><a href="../javadoc/com/google/appengine/api/users/package-summary.html">API Reference</a></li>

          </ul>
        </li>
      </ul>
    </li>
    <li><a href="../javadoc/index.html">Javadoc Reference</a></li>
    <li><a href="../jrewhitelist.html">JRE Class White List</a></li>
    <li><a href="../config/index.html">Configuration</a>
      <ul>
            <li><a href="../config/webxml.html">Deployment Descriptor</a></li>
    <li><a href="../config/appconfig.html">App Config</a></li>
    <li><a href="../config/indexconfig.html">Index Config</a></li>
    <li><a href="../config/cron.html">Scheduled Tasks</a></li>

      </ul>
    </li>
    <li><a href="../tools/index.html">Tools</a>
      <ul>
            <li><a href="../tools/devserver.html">Development Server</a></li>
    <li><a href="../tools/uploadinganapp.html">Uploading and Managing</a></li>
    <li><a href="../tools/eclipse.html">Google Plugin for Eclipse</a></li>
    <li><a href="../tools/ant.html">Using Apache Ant</a></li>

      </ul>
    </li>
    <li><a href="../howto/index.html">How-To</a>
      <ul>
              <li><a href="../howto/unittesting.html">Unit Testing</a></li>

      </ul>
    </li>

    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Python</h2>
    <ul>
          <li><a href="../../python/overview.html">Overview</a></li>
    <li><a href="../../python/runtime.html">CGI Environment</a></li>
    <li><a href="../../python/datastore/index.html">Storing Data</a>
      <ul>
             <li><a href="../../python/datastore/overview.html">Overview</a></li>
     <li><a href="../../python/datastore/entitiesandmodels.html">Entities and Models</a></li>
     <li><a href="../../python/datastore/creatinggettinganddeletingdata.html">Creating, Getting and Deleting Data</a></li>
     <li><a href="../../python/datastore/keysandentitygroups.html">Keys and Entity Groups</a></li>
     <li><a href="../../python/datastore/queriesandindexes.html">Queries and Indexes</a></li>
     <li><a href="../../python/datastore/transactions.html">Transactions</a></li>
     <li><a href="../../python/datastore/typesandpropertyclasses.html">Types and Property Classes</a></li>
     <li><a href="../../python/datastore/gqlreference.html">GQL Reference</a></li>

     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/datastore/modelclass.html">Model</a></li>
         <li><a href="../../python/datastore/expandoclass.html">Expando</a></li>
         <li><a href="../../python/datastore/polymodelclass.html">PolyModel</a></li>
         <li><a href="../../python/datastore/propertyclass.html">Property</a></li>
         <li><a href="../../python/datastore/queryclass.html">Query</a></li>
         <li><a href="../../python/datastore/gqlqueryclass.html">GqlQuery</a></li>
         <li><a href="../../python/datastore/keyclass.html">Key</a></li>
         <li><a href="../../python/datastore/functions.html">Functions</a></li>
         <li><a href="../../python/datastore/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

      </ul>
    </li>
    <li><a href="../../python/apis.html">Services</a>
      <ul>
        <li><a href="../../python/memcache/index.html">Memcache</a>
          <ul>
                 <li><a href="../../python/memcache/overview.html">Overview</a></li>
      <li><a href="../../python/memcache/usingmemcache.html">Using Memcache</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/memcache/clientclass.html">Client</a></li>
         <li><a href="../../python/memcache/functions.html">Functions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../../python/urlfetch/index.html">URL Fetch</a>
          <ul>
                 <li><a href="../../python/urlfetch/overview.html">Overview</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/urlfetch/fetchfunction.html">The fetch Function</a></li>
         <li><a href="../../python/urlfetch/responseobjects.html">Response Objects</a></li>
         <li><a href="../../python/urlfetch/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../../python/mail/index.html">Mail</a>
          <ul>
                 <li><a href="../../python/mail/overview.html">Overview</a></li>
     <li><a href="../../python/mail/sendingmail.html">Sending Mail</a></li>
     <li><a href="../../python/mail/attachments.html">Attachments</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/mail/emailmessageclass.html">EmailMessage</a></li>
         <li><a href="../../python/mail/emailmessagefields.html">Message Fields</a></li>
         <li><a href="../../python/mail/functions.html">Functions</a></li>
         <li><a href="../../python/mail/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../../python/images/index.html">Images</a>
          <ul>
                 <li><a href="../../python/images/overview.html">Overview</a></li>
     <li><a href="../../python/images/installingPIL.html">Installing PIL</a></li>
     <li><a href="../../python/images/usingimages.html">Using the Images API</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/images/imageclass.html">Image</a></li>
         <li><a href="../../python/images/functions.html">Functions</a></li>
         <li><a href="../../python/images/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../../python/users/index.html">Google Accounts</a>
          <ul>
                 <li><a href="../../python/users/overview.html">Overview</a></li>
     <li><a href="../../python/users/userobjects.html">User Objects</a></li>
     <li><a href="../../python/users/loginurls.html">Login URLs</a></li>
     <li><a href="../../python/users/adminusers.html">Admin Users</a></li>

     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/users/userclass.html">User</a></li>
         <li><a href="../../python/users/functions.html">Functions</a></li>
         <li><a href="../../python/users/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
      </ul>
    </li>
    <li><a href="../../python/config/index.html">Configuration</a>
      <ul>
            <li><a href="../../python/config/appconfig.html">App Config</a></li>
    <li><a href="../../python/config/indexconfig.html">Index Config</a></li>
    <li><a href="../../python/config/cron.html">Scheduled Tasks</a></li>

      </ul>
    </li>
    <li><a href="../../python/tools/index.html">Tools</a>
      <ul>
            <li><a href="../../python/tools/devserver.html">Development Server</a></li>
    <li><a href="../../python/tools/uploadinganapp.html">Uploading and Managing</a></li>
    <li><a href="../../python/tools/uploadingdata.html">Uploading Data</a></li>
    <li><a href="../../python/tools/webapp/index.html">webapp Framework</a>
      <ul>
             <li><a href="../../python/tools/webapp/overview.html">Overview</a></li>
     <li><a href="../../python/tools/webapp/running.html">Running the Application</a></li>
     <li><a href="../../python/tools/webapp/requesthandlers.html">Request Handlers</a></li>
     <li><a href="../../python/tools/webapp/requestdata.html">Request Data</a></li>
     <li><a href="../../python/tools/webapp/buildingtheresponse.html">Building the Response</a></li>
     <li><a href="../../python/tools/webapp/redirects.html">Redirects, Headers and Status Codes</a></li>
     

     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/tools/webapp/requestclass.html">Request</a></li>
         <li><a href="../../python/tools/webapp/responseclass.html">Response</a></li>
         <li><a href="../../python/tools/webapp/requesthandlerclass.html">RequestHandler</a></li>
         <li><a href="../../python/tools/webapp/wsgiapplicationclass.html">WSGIApplication</a></li>
         <li><a href="../../python/tools/webapp/utilmodule.html">Utility Functions</a></li>
         
       </ul>
     </li>

      </ul>
    </li>
    <li><a href="../../python/tools/libraries.html">Third-party Libraries</a></li>

      </ul>
    </li>
    <li><a href="../../python/howto/index.html">How-To</a>
      <ul>
              <li><a href="../../python/howto/usinggdataservices.html">Google Data Services</a></li>

      </ul>
    </li>

    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Managing Your App</h2>
    <ul>
      <li><a href="../../theadminconsole.html">The Admin Console</a></li>
      <li><a href="../../quotas.html">Quotas</a></li>
      <li><a href="../../billing.html">Billing</a></li>
    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Resources</h2>
    <ul>
      <li><a href="../../../kb/index.html">FAQ</a></li>
      <li><a href="../../../articles/index.html">Articles</a></li>
      <li><a href="http://appengine-cookbook.appspot.com/">Cookbook</a></li>
      <li><a href="http://appgallery.appspot.com/">App Gallery</a></li>
      <li><a href="http://code.google.com/p/googleappengine/">SDK Code</a></li>
      <li><a href="http://code.google.com/p/google-app-engine-samples/">Sample Apps Code</a></li>
      <li><a href="../../../community.html">Discussion Groups</a></li>
    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><a href="../../roadmap.html">Product Roadmap</a></li>
  <li><a href="http://code.google.com/p/googleappengine/wiki/SdkReleaseNotes">Release Notes</a></li>
  <li><a href="../../revision_history.html">Revision History</a></li>
</ul>

        <a class="hidden" href="#gc-topnav-anchor">More Google App Engine resource links</a>
      </div>

      <div class="g-unit" id="gc-pagecontent">
        <h1 class="page_title">Creating, Getting and Deleting Data</h1>



<p>Saving a JDO data object to the datastore is a simple matter of calling the <code>makePersistent()</code> method of the PersistenceManager instance.  The App Engine JDO implementation uses the primary key field of the object to keep track of which datastore entity corresponds with the data object, and can generate keys for new objects automatically.  You can use keys to retrieve entities quickly, and you can construct keys from known values (such as account IDs).</p>

<ul>
  <li><a href="#Making_Objects_Persistent">Making Objects Persistent</a></li>
  <li><a href="#Keys">Keys</a></li>
  <li><a href="#Creating_and_Using_Keys">Creating and Using Keys</a></li>
  <li><a href="#Getting_an_Object_By_Key">Getting an Object By Key</a></li>
  <li><a href="#Updating_an_Object">Updating an Object</a></li>
  <li><a href="#Deleting_an_Object">Deleting an Object</a></li>
</ul>

<h2 id="Making_Objects_Persistent">Making Objects Persistent</h2>

<p>To store a simple data object in the datastore, you call the PersistenceManager's <code>makePersistent()</code> method, passing it the instance.</p>

<pre class="prettyprint">
        PersistenceManager pm = PMF.get().getPersistenceManager();

        Employee e = new Employee("Alfred", "Smith", new Date());

        try {
            pm.makePersistent(e);
        } finally {
            pm.close();
        }
</pre>

<p>The call to <code>makePersistent()</code> is synchronous, and doesn't return until the object is saved and indexes are updated.</p>

<p>To save multiple objects in JDO, call the <code>makePersistentAll(...)</code> method with a Collection of objects.  In the current release, this is implemented similarly to a series of calls to <code>makePersistent()</code>.  In a future release, this method will perform more efficient batch calls to the datastore.</p>

<p class="note"><b>Note:</b> If any of the data object's persistent fields are references to other persistent data objects, and any of those objects have never been saved or have changed since they were loaded, the referenced objects will also be saved to the datastore.  See <a href="relationships.html">Relationships</a>.</p>


<h2 id="Keys">Keys</h2>

<p>Every entity has a key that is unique over all entities in App Engine.  A complete key includes several pieces of information, including the application ID, the kind, and an entity ID.  (Keys also contain information about entity groups; see <a href="transactions.html">Transactions</a> for more information.)</p>

<p>An object's key is stored in a field on the instance.  You identify the primary key field using the <code>@PrimaryKey</code> annotation.</p>

<p>The app can provide the ID portion of the key as a string when the object is created, or it can allow the datastore to generate a numeric ID automatically.  The complete key must be unique across all entities in the datastore.  In other words, an object must have an ID that is unique across all objects of the same kind and with the same entity group parent (if any).  You select the desired behavior of the key using the type of the field and annotations.</p>

<p>If the class is used as a "child" class in a relationship, the key field must be of a type capable of representing an entity group parent: either a Key instance, or a Key value encoded as a string.  See <a href="transactions.html">Transactions</a> for more information on entity groups, and <a href="relationships.html">Relationships</a> for more information on relationships.</p>

<p class="note"><b>Tip:</b> If the app creates a new object and gives it the same string ID as another object of the same kind (and the same entity group parent), saving the new object overwrites the other object in the datastore.  To detect whether a string ID is already in use prior to creating a new object, you can use a transaction to attempt to get an entity with a given ID, then create one if it doesn't exist.  See <a href="transactions.html">Transactions</a>.</p>

<p>There are 4 types of primary key fields:</p>

<dl>
<dt>Long</dt>
<dd>
  <p>A long integer (<code>java.lang.Long</code>), an entity ID automatically generated by the datastore.  Use this for objects without entity group parents whose IDs should be generated automatically by the datastore.  The long key field of an instance is populated when the instance is saved.</p>
<pre class="prettyprint">
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

// ...
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;
</pre>
</dd>

<dt>Unencoded String</dt>
<dd>
  <p>A string (<code>java.lang.String</code>), an entity ID ("key name") provided by the application when the object is created.  Use this for objects without entity group parents whose IDs should be provided by the application.  The application sets this field to the desired ID prior to saving.</p>
<pre class="prettyprint">
import javax.jdo.annotations.PrimaryKey;

// ...
    @PrimaryKey
    private String name;
</pre>
</dd>

<dt>Key</dt>
<dd>
  <p>A Key instance (<code>com.google.appengine.api.datastore.Key</code>).  The key value includes the key of the entity group parent (if any) and either the app-assigned string ID or the system-generated numeric ID.  To create the object with an app-assigned string ID, you create the Key value with the ID and set the field to the value.  To create the object with a system-assigned numeric ID, you leave the key field null.  (For information on how to use entity group parents, see <a href="transactions.html">Transactions</a>.)</p>
<pre class="prettyprint">
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;

// ...
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    public void setKey(Key key) {
        this.key = key;
    }
</pre>
  <p>The app can create a Key instance using the KeyFactory class:</p>
<pre class="prettyprint">
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

// ...
        Key key = KeyFactory.createKey(Employee.class.getSimpleName(), "Alfred.Smith@example.com");
        Employee e = new Employee();
        e.setKey(key);
        pm.makePersistent(e);
</pre>
</dd>

<dt>Key as Encoded String</dt>
<dd>
  <p>Similar to Key, but the value is the encoded string form of the key.  Encoded string keys allow you to write your application in a portable manner and still take advantage of App Engine datastore entity groups.</p>
<pre class="prettyprint">
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;

// ...
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    @Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
    private String encodedKey;
</pre>
  <p>The app can populate this value prior to saving using a key with a name, or it can leave it null.  If the encoded key field is null, the field is populated with a system-generated key when the object is saved.</p>
  <p>Key instances can be converted to and from the encoded string representation using the KeyFactory methods <code>keyToString()</code> and <code>stringToKey()</code>.</p>
  <p>When using encoded key strings, you can provide access to an object's string or numeric ID with an additional field:</p>
<pre class="prettyprint">
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    @Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
    private String encodedKey;

    @Persistent
    @Extension(vendorName="datanucleus", key="gae.pk-name", value="true")
    private String keyName;

    // OR:

    @Persistent
    @Extension(vendorName="datanucleus", key="gae.pk-id", value="true")
    private Long keyId;
</pre>
  <p>A <code>"gae.pk-name"</code> field can be set to a key name prior to saving the object.  When the object is saved, the encoded key field is populated with the complete key that includes the key name.  Its type must be String.</p>
  <p>A <code>"gae.pk-id"</code> field is populated when the object is saved, and cannot be modified.  Its type must be Long.</p>
</dl>

<p>When a new object with a generated key (a key field using <code>valueStrategy = IdGeneratorStrategy.IDENTITY</code>) is created, its key value starts out <code>null</code>.  The key field is populated when the object is written to the datastore.  If you are using a transaction, the object is written when the transaction is committed.  Otherwise, the object is written when the <code>makePersistent()</code> method is called if the object is being created, or when the PersistenceManager instance's <code>close()</code> method is called if the object is being updated.</p>


<h2 id="Creating_and_Using_Keys">Creating and Using Keys</h2>

<p>If the application knows every element of an entity's complete key, the application can create the corresponding <code>Key</code> object without the object.</p>

<p>For a key for an entity without an entity group parent, you can use the <code>createKey()</code> static method of the <code>KeyFactory</code> class.  This method takes a kind (the simple name of the class) and either an app-assigned string ID or a system-assigned numeric ID, and returns a <code>Key</code> object.  For example, to recreate the key of an entity of kind <code>"Employee"</code> with key name <code>"Alfred.Smith@example.com"</code> (and no entity group parent):</p>

<pre class="prettyprint">
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

// ...
        Key k = KeyFactory.createKey(Employee.class.getSimpleName(), "Alfred.Smith@example.com");
</pre>

<p>To recreate a key of an entity of kind <code>"Employee"</code> with a system-assigned numeric ID of <code>52234</code> (and no entity group parent):</p>

<pre class="prettyprint">
        Key k = KeyFactory.createKey(Employee.class.getSimpleName(), 52234);
</pre>

<p>Keys can be converted to and from a string representation using the KeyFactory class's <code>keyToString()</code> and <code>stringToKey()</code> methods, respectively.  (Note that this is different from the Key class's <code>toString()</code> method, which returns a human-readable value suitable for debugging.)</p>

<p>For a key for an entity with an entity group parent, you can use the KeyFactory.Builder class:</p>

<pre class="prettyprint">
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

// ...
        Key k = new KeyFactory.Builder(Employee.class.getSimpleName(), 52234).addChild(ExpenseReport.class.getSimpleName(), "A23Z79").getKey();
</pre>

<p>The Builder instance's <code>addChild()</code> method returns the Builder, so you can chain calls to add each element of the key path.  To get the complete Key value for a given builder, you call the Builder's <code>getKey()</code> method.</p>

<p>For more information about entity groups, see <a href="transactions.html">Transactions</a>.</p>


<h2 id="Getting_an_Object_By_Key">Getting an Object By Key</h2>

<p>To retrieve an object given its key, use the PersistenceManager's <code>getObjectById()</code> method.  The method takes the class for the object, and key:</p>

<pre class="prettyprint">
        Key k = KeyFactory.createKey(Employee.class.getSimpleName(), "Alfred.Smith@example.com");
        Employee e = pm.getObjectById(Employee.class, k);
</pre>

<p>If the class uses a key field that is an unencoded string ID (<code>String</code>) or numeric ID (<code>Long</code>), <code>getObjectByID()</code> can take the simple value as the key parameter:</p>

<pre class="prettyprint">
        Employee e = pm.getObjectById(Employee.class, "Alfred.Smith@example.com");
</pre>

<p>The key argument can be of any of the supported key field types (string ID, numeric ID, Key value, encoded key string), and can be of a different type than the key field in the class.  App Engine must be able to derive the complete key from the class name and the provided value.  String IDs and numeric IDs are exclusive, so a call using a numeric ID will never return an entity with a string ID.  If a Key value or encoded key string is used, the key must refer to an entity whose kind is represented by the class.</p>




<h2 id="Updating_an_Object">Updating an Object</h2>

<p>One way to update an object with JDO is to fetch the object, then modify it while the PersistenceManager that returned the object is still open.  Changes are persisted when the PersistenceManager is closed.  For example:
</p>
<pre class="prettyprint">
public void updateEmployeeTitle(User user, String newTitle) {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
        Employee e = pm.getObjectById(Employee.class, user.getEmail());
        if (titleChangeIsAuthorized(e, newTitle) {
            e.setTitle(newTitle);
        } else {
            throw new UnauthorizedTitleChangeException(e, newTitle);
        }
    } finally {
        pm.close();
    }
}
</pre>
<p>Since the <code>Employee</code> instance was returned by the PersistenceManager, the PersistenceManager knows about any modifications that are made to Persistent fields on the <code>Employee</code> and automatically updates the datastore with these modifications when the PersistenceManager is closed.  It know this because the Employee instance is "attached" to the PersistenceManager.</p>

<p>You can modify an object after the PersistenceManager has been closed by declaring the class as "detachable."  To do this, add the <code>detachable</code> attribute to the <code>@PersistenceCapable</code> annotation:</p>
<pre class="prettyprint">
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class Employee {
    // ...
}
</pre>

<p>Now you can read and write the fields of an Employee object after the PersistenceManager that loaded it has been closed.  The following example illustrates how a detached object might be useful:</p>
<pre class="prettyprint">
public Employee getEmployee(User user) {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    pm.setDetachAllOnCommit(true);
    try {
        e = pm.getObjectById(Employee.class, "Alfred.Smith@example.com");
    } finally {
        pm.close();
    }
    return e;
}

public void updateEmployeeTitle(Employee e, String newTitle) {
    if (titleChangeIsAuthorized(e, newTitle) {
        e.setTitle(newTitle);
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(e);
        } finally {
            pm.close();
        }
    } else {
        throw new UnauthorizedTitleChangeException(e, newTitle);
    }
}
</pre>

<p>Detached objects are a nice alternative to creating data transfer objects.  For more information on working with detached objects please see the <a href="http://www.datanucleus.org/products/accessplatform_1_1/jdo/attach_detach.html">DataNucleus documentation</a>.

<h2 id="Deleting_an_Object">Deleting an Object</h2>

<p>To delete an object from the datastore, call the PersistenceManager's <code>deletePersistent()</code> method with the object:</p>

<pre class="prettyprint">
        pm.deletePersistent(e);
</pre>

<p>If an object has fields containing child objects that are also persistent, the child objects are also deleted.  See <a href="relationships.html">Relationships</a> for more information.</pc>



      </div><!-- end gc-pagecontent -->
   </div><!-- end gooey wrapper -->

    </div> <!-- end codesite content -->

<div id="gc-footer" dir="ltr">
  <div class="text">
    
      <div class="notice"><div id="notice" style="text-align: center; border: 1em 0em 1em 0em">
  Except as otherwise <a
  href="http://code.google.com/policies.html#restrictions">noted</a>,
  the content of this page is licensed under the <a rel="license"
  href="http://creativecommons.org/licenses/by/2.5/">Creative Commons
  Attribution 2.5 License</a>, and code samples are licensed under the
  <a rel="license" href="http://www.apache.org/licenses/LICENSE-2.0">Apache
  2.0 License</a>.
<!-- <rdf:RDF xmlns="http://web.resource.org/cc/" 
              xmlns:dc="http://purl.org/dc/elements/1.1/"
              xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <Work rdf:about="">
    <license rdf:resource="http://creativecommons.org/licenses/by/2.5/" />
  </Work>
  <License rdf:about="http://creativecommons.org/licenses/by/2.5/">
    <permits rdf:resource="http://web.resource.org/cc/Reproduction"/>
    <permits rdf:resource="http://web.resource.org/cc/Distribution"/>
    <requires rdf:resource="http://web.resource.org/cc/Notice"/>
    <requires rdf:resource="http://web.resource.org/cc/Attribution"/>
    <permits rdf:resource="http://web.resource.org/cc/DerivativeWorks"/>
  </License>
</rdf:RDF> -->
</div>
Java is a registered trademark of Sun Microsystems, Inc.</div>
    
    &copy;2009 Google -
    <a href="http://code.google.com">Code Home</a> -
    <a href="http://www.google.com/accounts/TOS">Terms of Service</a> -
    <a href="http://www.google.com/privacy.html">Privacy Policy</a> -
    <a href="http://code.google.com/more">Site Directory</a>
    <br /> <br />
    Google Code offered in:
    <a href="http://code.google.com/intl/en">English</a> -
    <a href="http://code.google.com/intl/es">Español</a> -
    <a href="http://code.google.com/intl/ja">日本語</a> -
    <a href="http://code.google.com/intl/ko">한국어</a> -
    <a href="http://code.google.com/intl/pt-BR">Português</a> -
    <a href="http://code.google.com/intl/ru">Pусский</a> -
    <a href="http://code.google.com/intl/zh-CN">中文(简体)</a> -
    <a href="http://code.google.com/intl/zh-TW">中文(繁體)</a>
  </div>
</div><!-- end gc-footer -->

</div><!-- end gc-containter -->

<script type="text/javascript">CODESITE_CSITimer['load'].tick('ats');</script>
<script src="../../../../js/codesite_tail.pack.04102009.js" type="text/javascript"></script>






  </body>
</html>


